package com.example.demo.arithmetic.datastructure.graph;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class TopologicalSort {
    public static void main(String[] args) {
        Vertex v1 = new Vertex("网页基础");
        Vertex v2 = new Vertex("Java基础");
        Vertex v3 = new Vertex("JavaWeb");
        Vertex v4 = new Vertex("Spring");
        Vertex v5 = new Vertex("微服务");
        Vertex v6 = new Vertex("数据库");
        Vertex v7 = new Vertex("实战项目");

        v1.edges = List.of(new Vertex.Edge(v3));
        v2.edges = List.of(new Vertex.Edge(v3));
        v3.edges = List.of(new Vertex.Edge(v4));
        v6.edges = List.of(new Vertex.Edge(v4));
        v4.edges = List.of(new Vertex.Edge(v5));
        v5.edges = List.of(new Vertex.Edge(v7));
        v7.edges = List.of();

        List<Vertex> graph = new ArrayList<>(List.of(v1, v2, v3, v4, v5, v6, v7));
        // 统计每个节点的入度
        for (Vertex vertex : graph) {
            for (Vertex.Edge edge : vertex.edges) {
                edge.linked.inDegree++;
            }
        }

//        for (Vertex vertex : graph) {
//            System.out.println(vertex.name + "-" + vertex.inDegree);
//        }

        // 将入度为0的顶点加入队列
        LinkedList<Vertex> queue = new LinkedList<>();
        for (Vertex vertex : graph) {
            if (vertex.inDegree == 0) {
                queue.offer(vertex);
            }
        }
        //队列中不断移除顶点，每移出一个盯点，相邻顶点度减1 若减到0
        while (!queue.isEmpty()) {
            Vertex poll = queue.poll();
            System.out.println(poll.name);
            for (Vertex.Edge edge : poll.edges) {
                edge.linked.inDegree--;
                if (edge.linked.inDegree == 0) {
                    queue.offer(edge.linked);
                }
            }
        }
    }
}

